const XLSX = require('xlsx');
const fs = require('fs');
const path = require('path');

function excelToJson(excelFilePath, outputFolderPath) {
    // 读取 Excel 文件
    const workbook = XLSX.readFile(excelFilePath);

    // 处理第一个工作表（非 uni-app）
    const nonUniAppSheet = workbook.Sheets['智源APP'];
    const nonUniAppData = XLSX.utils.sheet_to_json(nonUniAppSheet, { header: 1 });
    const nonUniAppHeaders = nonUniAppData[0];
    const nonUniAppLangs = nonUniAppHeaders.slice(2);
    const nonUniAppAllData = {};

    nonUniAppLangs.forEach(lang => {
        nonUniAppAllData[lang] = {};
    });

    for (let i = 1; i < nonUniAppData.length; i++) {
        const row = nonUniAppData[i];
        const id = row[0];
        for (let j = 2; j < nonUniAppHeaders.length; j++) {
            const lang = nonUniAppHeaders[j];
            nonUniAppAllData[lang][id] = row[j];
        }
    }

    // 保存非 uni-app 的 JSON 文件
    nonUniAppLangs.forEach(lang => {
        const jsonData = JSON.stringify(nonUniAppAllData[lang], null, 2);
        const filePath = path.join(outputFolderPath, `${lang}.json`);
        fs.writeFileSync(filePath, jsonData);
        console.log(`已生成非 uni-app JSON 文件：${filePath}`);
    });

    // 处理第二个工作表（uni-app）
    const uniAppSheet = workbook.Sheets['uni-app'];
    if (uniAppSheet) {
        const uniAppData = XLSX.utils.sheet_to_json(uniAppSheet, { header: 1 });
        const uniAppHeaders = uniAppData[0];
        const uniAppLangs = uniAppHeaders.slice(2);
        const uniAppAllData = {};

        uniAppLangs.forEach(lang => {
            uniAppAllData[lang] = {};
        });

        for (let i = 1; i < uniAppData.length; i++) {
            const row = uniAppData[i];
            const id = row[0];
            const description = row[1];
            for (let j = 2; j < uniAppHeaders.length; j++) {
                const lang = uniAppHeaders[j];
				if(!description){
					uniAppAllData[lang][id] = row[j];
				}else {
					if (!uniAppAllData[lang][description]) {
						uniAppAllData[lang][description] = {};
					}
					uniAppAllData[lang][description][id] = row[j];
				}
            }
        }

        // 保存 uni-app 的 JSON 文件
        uniAppLangs.forEach(lang => {
            const jsonData = JSON.stringify(uniAppAllData[lang], null, 2);
            const filePath = path.join(outputFolderPath, `uni-app.${lang}.json`);
            fs.writeFileSync(filePath, jsonData);
            console.log(`已生成 uni-app JSON 文件：${filePath}`);
        });
    }
}

// 使用示例
const excelFilePath = path.join(__dirname, '../locale/智源APP多语言文件.xlsx');
const outputFolderPath = path.join(__dirname, '../locale');

// 确保输出文件夹存在
if (!fs.existsSync(outputFolderPath)) {
    fs.mkdirSync(outputFolderPath, { recursive: true });
}

excelToJson(excelFilePath, outputFolderPath);
